<?php

include_once("../info_struct.php");

/*
 Usage:
doi_get_by_string(string);
paramter:
string - search string

return:
class infos
see info_struct.php for content of the class
false - if all went wrong / id not found
*/
function doi_get_by_string($string) {
    $return = array();

    $search = str_replace(" ", "%20", $string);

    if(function_exists('curl_version')) {
        include_once("../helper_funcs.php");
        $content = curl_file_get_contents("http://search.crossref.org/dois?q=".$search."&rows=7");
    } else {
        $content = file_get_contents("http://search.crossref.org/dois?q=".$search."&rows=7");
    }
    if ($content === false)
        return false;


    $json = json_decode($content);
    if ($json === false)
        return false;

    foreach ($json as $entry) {
        if ((string)$entry->year) {
            $new_entry = new infos();

            $new_entry->title = (string)$entry->title;
            $new_entry->doi = substr((string)$entry->doi, 18);
            $new_entry->year = (string)$entry->year;

            $new_entry->author = substr((string)$entry->fullCitation, 0, strpos((string)$entry->fullCitation, $new_entry->year)-2);

            if (preg_match("/<i>(.*)<\/i>/", (string)$entry->fullCitation, $journal) === 1)
                $new_entry->journal = $journal[1];
            	
            if (preg_match("/\d+-\d+/", (string)$entry->fullCitation, $pages) === 1)
                $new_entry->pages = $pages[0];
            	
            $new_entry->from = "doi";

            array_push($return, $new_entry);
        }
    }

    return $return;
}

/*
 Usage:
doi_get_by_id(id);
paramter:
id - search for the meta data of the id

return:
class infos
see info_struct.php for content of the class
false - if all went wrong / id not found
*/
function doi_get_by_id($id) {
    $return = array();

    if(function_exists('curl_version')) {
        include_once("../helper_funcs.php");
        $content = curl_file_get_contents("http://search.crossref.org/dois?q=".$id."&rows=7");
    } else {
        $content = file_get_contents("http://search.crossref.org/dois?q=".$id."&rows=7");
    }
    if ($content === false)
        return false;

    $json = json_decode($content);
    if ($json === false)
        return false;

    foreach ($json as $entry) {
        $new_entry = new infos();

        $new_entry->title = (string)$entry->title;
        $new_entry->doi = (string)$id;
        $new_entry->year = (string)$entry->year;

        $new_entry->author = substr((string)$entry->fullCitation, 0, strpos((string)$entry->fullCitation, $new_entry->year)-2);

        if (preg_match("/<i>(.*)<\/i>/", (string)$entry->fullCitation, $journal) === 1)
            $new_entry->journal = $journal[1];
        	
        if (preg_match("/\d+-\d+/", (string)$entry->fullCitation, $pages) === 1)
            $new_entry->pages = $pages[0];

        $new_entry->from = "doi";

        array_push($return, $new_entry);
    }

    return $return[0];
}
?>